/**
 * 树形目录管理模块
 */
class TreeManager {
    constructor() {
        this.tree = null;
        this.layer = null;
        this.currentConfig = null;
        this.connectionId = null;
        this.isLoading = false;
        
        this.init();
    }

    init() {
        // 等待layui加载完成
        layui.use(['tree', 'layer'], (tree, layer) => {
            this.tree = tree;
            this.layer = layer;
            this.setupUI();
            this.bindEvents();
        });
    }

    setupUI() {
        this.createConnectionForm();
        this.setupConfigToggle();
    }

    createConnectionForm() {
        const configContent = document.getElementById('configContent');
        configContent.innerHTML = `
            <div class="connection-form">
                <div class="form-row">
                    <div class="form-group">
                        <label class="form-label">主机名</label>
                        <input type="text" id="hostName" class="form-input" placeholder="如: server1" value="云主机">
                    </div>
                    <div class="form-group">
                        <label class="form-label">IP地址</label>
                        <input type="text" id="hostIP" class="form-input" placeholder="192.168.1.100" value="10.21.162.157">
                    </div>
                    <div class="form-group small">
                        <label class="form-label">端口</label>
                        <input type="number" id="hostPort" class="form-input" value="22">
                    </div>
                </div>
                <div class="form-row">
                    <div class="form-group">
                        <label class="form-label">用户名</label>
                        <input type="text" id="username" class="form-input" placeholder="root" value="root">
                    </div>
                    <div class="form-group">
                        <label class="form-label">密码</label>
                        <input type="password" id="password" class="form-input">
                    </div>
                </div>
                <div class="form-row">
                    <div class="form-group large">
                        <label class="form-label">初始路径</label>
                        <input type="text" id="remotePath" class="form-input" value="/home/mm" placeholder="/home/user">
                    </div>
                    <div class="form-group small">
                        <label class="form-label">最大深度</label>
                        <input type="number" id="maxDepth" class="form-input" value="3" min="1" max="10">
                    </div>
                </div>
                <div class="form-actions">
                    <button class="btn-small btn-primary" onclick="TreeManager.testConnection()">测试连接</button>
                    <button class="btn-small btn-success" onclick="TreeManager.loadTree()">加载目录</button>
                </div>
            </div>
        `;
    }

    setupConfigToggle() {
        const toggleBtn = document.getElementById('toggleConfig');
        const configContent = document.getElementById('configContent');
        const configHeader = document.querySelector('.config-header');

        configHeader.addEventListener('click', () => {
            const isExpanded = configContent.classList.contains('expanded');
            
            if (isExpanded) {
                configContent.classList.remove('expanded');
                toggleBtn.classList.remove('expanded');
                configContent.style.maxHeight = '0';
            } else {
                configContent.classList.add('expanded');
                toggleBtn.classList.add('expanded');
                configContent.style.maxHeight = configContent.scrollHeight + 'px';
            }
        });

        // 默认展开
        setTimeout(() => {
            configContent.classList.add('expanded');
            toggleBtn.classList.add('expanded');
            configContent.style.maxHeight = configContent.scrollHeight + 'px';
        }, 100);
    }

    bindEvents() {
        // 监听socket事件
        window.socketClient.on('socketConnect', () => {
            this.updateConnectionStatus('已连接到服务器', 'success');
        });

        window.socketClient.on('socketDisconnect', () => {
            this.updateConnectionStatus('与服务器断开连接', 'error');
        });

        window.socketClient.on('connectionResult', (data) => {
            this.handleConnectionResult(data);
        });

        window.socketClient.on('eventResult', (data) => {
            this.handleEventResult(data);
        });
    }

    // 获取配置信息
    getConfig() {
        return {
            name: document.getElementById('hostName').value.trim(),
            host: document.getElementById('hostIP').value.trim(),
            port: document.getElementById('hostPort').value,
            username: document.getElementById('username').value.trim(),
            password: document.getElementById('password').value,
            remote_path: document.getElementById('remotePath').value.trim(),
            max_depth: document.getElementById('maxDepth').value
        };
    }

    // 验证配置
    validateConfig() {
        const config = this.getConfig();
        if (!config.name || !config.host || !config.username || !config.password || !config.remote_path) {
            this.showError('请填写完整的服务器配置信息');
            return false;
        }
        return true;
    }

    // 测试连接
    testConnection() {
        if (!this.validateConfig()) {
            return;
        }

        this.showStatus('正在连接远程主机...');
        const config = this.getConfig();
        this.currentConfig = config;
        
        window.socketClient.loginRemote(config);
    }

    // 加载目录树
    loadTree() {
        if (!this.validateConfig()) {
            return;
        }

        const config = this.getConfig();
        this.currentConfig = config;
        
        this.showLoading(true);
        document.getElementById('directoryTree').innerHTML = '';
        this.showStatus('正在加载目录: ' + config.remote_path);

        const hostKey = `${config.name}|${config.host}:${config.port}|${config.username}`;
        const commandConfig = {
            cmd_event: "tree",
            params: [config.remote_path, config.max_depth],
            hosts_key: [hostKey]
        };

        window.socketClient.sendCommand(commandConfig);
    }

    // 刷新目录树
    refreshTree() {
        if (this.currentConfig) {
            this.loadTree();
        } else {
            this.layer.msg('请先加载目录树');
        }
    }

    // 处理连接结果
    handleConnectionResult(data) {
        console.log('收到连接结果:', data);
        if (data.success) {
            this.showStatus(data.msg);
            this.updateDrawerConnectionInfo();
        } else {
            this.showError(data.msg);
        }
    }

    // 处理事件结果
    handleEventResult(data) {
        this.showLoading(false);
        
        if (data.success && data.cmd_event === 'tree') {
            this.renderTree(data.data[0].content);
            this.showStatus(data.msg);
            this.updateDrawerConnectionInfo();
        } else {
            this.showError(data.msg);
        }
    }

    // 渲染树形结构
    renderTree(treeData) {
        if (!this.tree) return;

        this.tree.render({
            elem: '#directoryTree',
            data: treeData,
            showCheckbox: false,
            id: 'directoryTreeId',
            isJump: false,
            accordion: true,
            click: (obj) => {
                console.log('选中:', obj.data.field);
                // 更新路径输入框
                document.getElementById('remotePath').value = obj.data.field;
                // 更新当前路径显示
                document.getElementById('currentPathDisplay').textContent = obj.data.field;
                // 更新抽屉中的当前路径
                const currentPathElement = document.getElementById('currentPath');
                if (currentPathElement) {
                    currentPathElement.textContent = obj.data.field;
                }
            }
        });
    }

    // 显示加载状态
    showLoading(show) {
        const loading = document.getElementById('loading');
        this.isLoading = show;
        loading.style.display = show ? 'block' : 'none';
    }

    // 显示状态信息
    showStatus(message) {
        const statusInfo = document.getElementById('statusInfo');
        const statusText = document.getElementById('statusText');
        const errorInfo = document.getElementById('errorInfo');
        
        statusText.textContent = message;
        statusInfo.style.display = 'block';
        errorInfo.style.display = 'none';
    }

    // 显示错误信息
    showError(message) {
        const statusInfo = document.getElementById('statusInfo');
        const errorInfo = document.getElementById('errorInfo');
        const errorText = document.getElementById('errorText');
        
        errorText.textContent = message;
        errorInfo.style.display = 'block';
        statusInfo.style.display = 'none';
    }

    // 更新连接状态
    updateConnectionStatus(message, type) {
        if (type === 'success') {
            this.showStatus(message);
        } else {
            this.showError(message);
        }
    }

    // 更新抽屉中的连接信息
    updateDrawerConnectionInfo() {
        if (!this.currentConfig) return;

        const connectionStatus = document.getElementById('connectionStatus');
        const currentHost = document.getElementById('currentHost');
        const treeDepth = document.getElementById('treeDepth');

        if (connectionStatus) {
            connectionStatus.textContent = '已连接';
            connectionStatus.style.color = '#52c41a';
        }

        if (currentHost) {
            currentHost.textContent = `${this.currentConfig.name} (${this.currentConfig.host})`;
        }

        if (treeDepth) {
            treeDepth.textContent = this.currentConfig.max_depth;
        }
    }
}

// 创建全局TreeManager实例
window.TreeManager = new TreeManager();